import { FC, useEffect, useState } from "react";
import { css } from "@emotion/css";
import { DatePicker, Form, Popover, Button } from "@arco-design/web-react";
import { IconRefresh } from "@arco-design/web-react/icon";
import { useAPI } from "../../hooks/useAPI.ts";
import dayjs from "dayjs";
import Box from "@mui/material/Box";

export const disableFutureDates = (current: any) => {
  return current.isAfter(dayjs());
};

export function getNursingReport(
  startTime: any,
  roomId: number | string,
  api: any
): Promise<any> {
  return api.getNursingReport({
    roomId,
    startTime,
  });
}

let reversedArray = [
  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
  22, 23,
];

function parseTime(timeStr: string) {
  const [hours, minutes] = timeStr.split(":").map(Number);
  return hours * 60 + minutes;
}

// 定义一个函数来提取时间范围的开始时间
function getStartTime(timeRange: any) {
  const startTime = timeRange.split("-")[0];
  return parseTime(startTime);
}

export const mergeTime = (arr: any) => {
  // 将时间字符串转换为分钟数
  const timeToMinutes = (timeStr: any) => {
    const [hours, minutes] = timeStr.split(":").map(Number);
    return hours * 60 + minutes;
  };
  return arr.map((current: any) => {
    // 初始化结果（包含自身）
    const result = {
      ...current,
      title: [
        {
          time: `${current.startTimeStr}-${current.endTimeStr}`,
          action: current.action,
        },
      ],
      num: current.minutes,
    };
    // 如果width > 6，直接返回自身
    if (current.width > 1) {
      result.num =
        Math.floor(result.num / 60) + "小时" + (result.num % 60) + "分钟";
      return result;
    }
    // width <= 6 时，检查其他项
    const currentStart = timeToMinutes(current.startTimeStr);
    const currentEnd = timeToMinutes(current.endTimeStr);

    arr.forEach((other: any) => {
      // 跳过自身比较
      if (current === other) return;
      const otherStart = timeToMinutes(other.startTimeStr);
      const otherEnd = timeToMinutes(other.endTimeStr);
      // 计算时间差（取绝对值）
      const timeDiff = Math.min(
        Math.abs(currentStart - otherStart),
        Math.abs(currentStart - otherEnd),
        Math.abs(currentEnd - otherStart),
        Math.abs(currentEnd - otherEnd)
      );
      // 如果时间差小于10分钟，则视为相关
      if (timeDiff < 1) {
        result.title.push({
          time: `${other.startTimeStr}-${other.endTimeStr}`,
          action: other.action,
        });
        result.num += other.minutes;
      }
    });
    result.num =
      Math.floor(result.num / 60) + "小时" + (result.num % 60) + "分钟";
    result.title.sort((a: any, b: any) => {
      const startTimeA = getStartTime(a.time);
      const startTimeB = getStartTime(b.time);
      return startTimeA - startTimeB;
    });
    return result;
  });
};
const minutesFromMidnight = (timestamp: number, date: any) => {
  // 获取当前日期零点的时间戳
  const now = new Date(date);
  const startOfDay = now.getTime();
  // 计算时间差（毫秒）
  const diffInMilliseconds = timestamp - startOfDay;
  // 将毫秒转换为分钟
  const diffInMinutes = Math.floor(diffInMilliseconds / (1000 * 60));
  return diffInMinutes;
};

export const NursingReport: FC<{ roomId: number | string }> = ({ roomId }) => {
  const [dateRange, setDateRange] = useState([
    dayjs().format("YYYY-MM-DD"),
    dayjs().format("YYYY-MM-DD"),
  ]);
  const [data, setData] = useState([]);

  const [refresh, setRefresh] = useState(false);
  // const [loding, setLoading] = useState(false);

  const api = useAPI();

  useEffect(() => {
    setData([]);
    getNursingReport(dateRange[0], roomId, api).then((response) => {
      const data = response.data?.data;
      const sortData = data.sort((a: any, b: any) =>
        b.userType.localeCompare(a.userType)
      );
      let list = sortData.map((item: any) => {
        let minutesDiff = item.activityRecords.map((time: any) => {
          // 获取时间戳
          const startTime =
            new Date(time.startTime).getTime() + 8 * 3600 * 1000;
          const endTime = new Date(time.endTime).getTime() + 8 * 3600 * 1000;
          // 将毫秒转换为分钟
          // 直接计算时间差（毫秒）
          const diff = Math.abs(endTime / 1000 - startTime / 1000);
          // 将毫秒转换为分钟
          const minutes = Math.round(diff / 60);
          const minutesDiff = Number(((minutes / 10) * 6).toFixed(2));
          return {
            left: (
              (minutesFromMidnight(startTime, dateRange[0]) / 10) *
              6
            ).toFixed(2),
            width: minutesDiff < 2 ? 2 : minutesDiff,
            minutes,
            minutesStr:
              Math.floor(minutes / 60) + "小时" + (minutes % 60) + "分钟",
            startTimeStr: dayjs(time.startTime).format("HH:mm"),
            endTimeStr: dayjs(time.endTime).format("HH:mm"),
            startTime,
            endTime,
            action: time.action,
          };
        });

        let stayTime = minutesDiff.reduce(
          (accumulator: any, currentValue: any) => {
            return accumulator + currentValue.minutes;
          },
          0
        ); // 初始值为0
        var hours = Math.floor(stayTime / 60);
        var remainingMinutes = Math.round(stayTime % 60);
        return {
          ...item,
          name: item.userType == "worker" ? "工作人员" : item.userName,
          diff: mergeTime(minutesDiff),
          sumTime: hours + "小时" + remainingMinutes + "分钟",
          textColor:
            item.userType == "worker"
              ? "#798AFF"
              : "#FF9800",
          bgColor:
            item.userType == "worker"
              ? "#F3F4FF"
              : "#FFF4E4",
        };
      });
      setData(list);
      // console.log("list===", list);
    });
  }, [refresh, dateRange]);

  return (
    <div>
      <h3
        className={css`
          border-left: 3px solid rgb(var(--primary-6));
          padding-left: 12px;
          border-radius: 2px;
          margin-bottom: 30px;
        `}
      >
        护理报告
      </h3>
      <div
        className={css`
          display: flex;
          justify-content: space-between;
        `}
      >
        <Form layout="inline">
          <Form.Item label="日期查询：">
            <DatePicker
              onChange={(e) => {
                setDateRange([e, e]);
                setRefresh(!refresh);
              }}
              onClear={() => {
                setDateRange(["", ""]);
              }}
              disabledDate={disableFutureDates}
              defaultValue={dateRange[0]}
            />
          </Form.Item>
        </Form>
        <Button
          type="outline"
          htmlType="button"
          onClick={() => {
            setRefresh(!refresh);
          }}
          icon={<IconRefresh />}
        >
          刷新
        </Button>
      </div>

      <Box
        sx={{
          width: "100%",
          marginTop: "16px",
        }}
      >
        {data.length > 0 ? (
          <div
            className={css`
              width: 100%;
              overflow-x: auto;
            `}
          >
            <div
              className={css`
                width: 100%;
                min-width: 984px;
              `}
            >
              {data.map((v: any, i: number) => (
                <div
                  key={i}
                  className={css`
                    display: flex;
                  `}
                >
                  <div
                    className={css`
                      display: inline-block;
                      width: 105px;
                      height: 46px;
                      font-size: 12px;
                      line-height: 46px;
                      color: #fff;
                      text-align: center;
                      border-radius: 4px;
                      background: ${v.textColor};
                    `}
                  >
                    {v.userName}
                  </div>
                  <div
                    className={css`
                      position: relative;
                      display: flex;
                      background: ${v.bgColor};
                    `}
                  >
                    {/* 护工进出时间 */}
                    {v.diff.map((timeValue: any, timeIndex: number) => (
                      <div
                        key={timeIndex}
                        className={css`
                          position: absolute;
                          left: ${timeValue.left}px;
                          top: 9px;
                          width: ${timeValue.width}px;
                          height: 28px;
                          background: ${v.textColor};
                          border-radius: 2px;
                          cursor: pointer;
                          z-index: 999;
                        `}
                      >
                        <Popover
                          trigger="hover"
                          content={
                            <span
                              className={css`
                                color: #796060;
                              `}
                            >
                              {timeValue.title.map(
                                (title: any, titleIndex: number) => (
                                  <p
                                    className={css`
                                      font-size: 14px;
                                    `}
                                    key={titleIndex}
                                  >
                                    {title.time}&nbsp;&nbsp;{title.action}
                                  </p>
                                )
                              )}
                              <p>共计 {timeValue.num}</p>
                            </span>
                          }
                        >
                          <div
                            className={css`
                              width: 100%;
                              height: 100%;
                            `}
                          ></div>
                        </Popover>
                      </div>
                    ))}
                    {/* 虚线框、底部时间轴 */}
                    {reversedArray.map((num, index) => (
                      <div
                        key={index}
                        className={css`
                          position: relative;
                          width: 36px;
                          height: 100%;
                          border-right: 1px dashed ${v.textColor};
                        `}
                      >
                        <div
                          className={css`
                            width: 100%;
                            position: absolute;
                            left: -4px;
                            bottom: -24px;
                            color: #8e8a82;
                            font-size: 12px;
                          `}
                        >
                          {i + 1 === data.length ? num : ""}
                          {i + 1 === data.length &&
                            index + 1 === reversedArray.length && (
                              <div
                                className={css`
                                  position: absolute;
                                  right: -12px;
                                  bottom: 0;
                                `}
                              >
                                24
                              </div>
                            )}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              ))}
            </div>

            {/* 统计 */}
            <div
              className={css`
                margin-top: 42px;
                display: flex;
                justify-content: center;
                flex-wrap: wrap;
              `}
            >
              {data.map((v: any, i) => (
                <div
                  key={i}
                  className={css`
                    margin: 10px 30px;
                    color: #3d3d3d;
                    line-height: 25px;
                  `}
                >
                  <div
                    className={css`
                      display: flex;
                      align-items: center;
                      font-size: 14px;
                      color: #767067;
                    `}
                  >
                    <div
                      className={css`
                        width: 40px;
                        height: 20px;
                        background: ${v.textColor};
                        border-radius: 4px;
                        margin-right: 8px;
                      `}
                    ></div>
                    <div>{v.userName}进入时间</div>
                  </div>
                  <div>总进入次数：{v.enterRoomCount}次</div>
                  <div>总计：{v.sumTime}</div>
                </div>
              ))}
            </div>
          </div>
        ) : (
          <div
            className={css`
              text-align: center;
              margin-top: 52px;
            `}
          >
            暂无数据
          </div>
        )}
      </Box>
    </div>
  );
};
